package server;

import java.util.logging.Level;

import rmi.server.MessageRemote;
import rmi.server.ServerRemote;
import rmi.server.UserRemote;
import toolkit.Logger;

public class Server
{
	public static final String NAME = "Project Poker";
	
	private static Logger logger = new Logger();
	
	public Server()
	{
		// Add a hook for when the application closes.
		Runtime.getRuntime().addShutdownHook(new Thread()
		{
			public void run()
			{
				
			}
		});
	}

	public static Logger getLogger()
	{
		return logger;
	}
	
	public void run()
	{
		// We create a separate thread to handle the clients, because has to be kept open
		// in order to handle multiple clients.
		new InitializeServer().start();
		
		logger.log(Level.INFO, "Ready to accept clients.");
		
		try
		{
			// Start the RMI server.
			rmi.Server server = new rmi.Server();
			
			// This is the main entrance to the server.
			// It contains references to the poker domain object,
			// thus it can reach to every reachable instance on the server side.
			server.setServerObject("server", ServerRemote.getInstance());
			
			// The entrance for all user related domain objects.
			server.setServerObject("user", UserRemote.getInstance());
			
			// The entrance for all message (like mail and chat) related domain objects.
			server.setServerObject("message", MessageRemote.getInstance());
			
			logger.log(Level.INFO, "Successfully started the RMI server.");
		}
		catch (Exception e)
		{
			closeServer(e);
		}
		
		logger.log(Level.INFO, "Successfully dispatched the server.");
	}
	
	private void closeServer(Exception e)
	{
		logger.log(Level.SEVERE, "Something went wrong when trying to dispatch the server.\n" +
				"The application will be closed.", e);
	}
	
	public static void main(String[] arguments)
	{
		Server server = new Server();
		server.run();
	}
}